<template>
  <div class="login-wrap">
    <div class="login-container">
      <div class="login-container__aside-img-container">
        <img src="@/assets/svg/fighting.svg" alt="抗疫必胜" />
      </div>
      <div class="login-container__form-container">
        <el-form
          ref="ruleFormRef"
          :model="loginForm"
          status-icon
          :rules="rules"
          class="login-container__form"
        >
          <h1>登 录</h1>
          <el-form-item prop="id">
            <el-input v-model="loginForm.id" size="large" placeholder="账号">
              <template #prefix>
                <el-icon>
                  <IEpUser />
                </el-icon>
                <el-divider direction="vertical" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              size="large"
              type="password"
              placeholder="密码"
              show-password
            >
              <template #prefix>
                <el-icon>
                  <IEpLock />
                </el-icon>
                <el-divider direction="vertical" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="captcha">
            <el-input
              v-model="loginForm.captcha"
              size="large"
              placeholder="验证码"
              style="width: 280px"
            />
            <el-image @click="reloadCaptcha" key="fill" :src="captchaUrl">
              <template #error>
                <div class="image-slot">
                  <el-icon><IEpPicture /></el-icon>
                </div>
              </template>
            </el-image>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="resetForm(formRef)"
              >重置
            </el-button>
            <el-button type="primary" @click="handleLogin(formRef)"
              >登录
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
// 获取 element 组件中的属性类型
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { validId, validatePassword, validCaptcha } from '@/utils/validate'
import { getCaptcha, login } from '@/api/modules/login'
import useMainStore from '@/store/modules/user'
import { useRouter } from 'vue-router'
import { getUUID } from '@/utils/uuid'

// ------------------------------ 表单 ------------------------------
// 登录表单
const loginForm = reactive({
  id: 10115613,
  password: '123456',
  captcha: '',
})
// 表单实例
const formRef = ref<FormInstance>()
// 表单规则
const rules = reactive<FormRules>({
  id: [{ validator: validId, trigger: 'blur' }],
  password: [{ validator: validatePassword, trigger: 'blur' }],
  captcha: [{ validator: validCaptcha, trigger: 'blur' }],
})
// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

// ------------------------------ 验证码 ------------------------------
// TODO 使用blob类型接收验证码
// 验证码URL
const captchaUrl = ref()
// 刷新验证码
let uuid: string = ''
const reloadCaptcha = () => {
  uuid = window.sessionStorage.getItem('captcha_key') as string
  getCaptcha(uuid)
    .then((response) => {
      captchaUrl.value = window.URL.createObjectURL(new Blob([response]))
    })
    .catch((error) => {
      console.log(error)
    })
}

// ------------------------------ 登录 ------------------------------
const router = useRouter()
const { setToken } = useMainStore()
const handleLogin = async (formRef: FormInstance | undefined) => {
  login(loginForm, uuid).then((res: IResponse) => {
    const code = res.code
    const message = res.message
    if (code === '00000') {
      const { tokenValue } = res.data
      setToken(tokenValue)
      router.replace({ path: '/layout' })
    } else {
      ElMessage.error(message)
    }
  })
}

// ------------------------------ 挂载 ------------------------------

onMounted(() => {
  // 退出后强刷新，清除动态路由，以此实现其他角色登录
  if (router.hasRoute('首页')) {
    history.pushState(null, '', document.URL)
    router.go(0)
  }
  // 给后端 redis 当做唯一键名

  if (window.sessionStorage.getItem('captcha_key') == null) {
    uuid = getUUID(16, 62)

    window.sessionStorage.setItem('captcha_key', uuid)
  }
  reloadCaptcha()
})
</script>

<style lang="scss" scoped>
/* 让svg背景文件根据浏览器窗口的大小实现自适应伸缩 */
.login-wrap {
  position: absolute;
  width: 100%;
  height: 100%;
  background-attachment: fixed;
  background-color: #a0cfff;
  background-image: url(@/assets/svg/login-background.svg);
  background-size: 100% 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-container {
  background: rgba(236, 245, 255, 0.5);
  width: 800px;
  height: 420px;
  border-radius: 10px;
  backdrop-filter: blur(4px);
  padding: 10px;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-items: stretch;
}
.login-container__aside-img-container {
  flex: 400px 0 0;
}
img {
  width: 100%;
}
.login-container__form-container {
  display: flex;
  flex: auto 1 0;
  justify-content: center;
  align-items: center;
}
.login-container__form {
  text-align: center;
}
.el-image {
  width: 80px;
  height: 40px;
  cursor: pointer;
}
</style>
